#!/bin/sh
#
# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 66 34
# description: Lancement de PreFork
#
SERVICE=PreFork
USER=jmrenouard
BASEDIR=/home/jmrenouard
PID_FILE=/tmp/server.pid
EXEC_FILE=/home/jmrenouard/prefork.pl
INTERPERTER=/usr/bin/perl


lsb_functions="/lib/lsb/init-functions"
if test -f $lsb_functions ; then
source $lsb_functions
    else
log_success_msg()
{
    echo " SUCCESS! $@"
}
log_failure_msg()
{
    echo " ERROR! $@"
}
fi

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

mode=$1    # start or stop

cd $BASEDIR

case "$mode" in
'start')
# Start service
echo  -en "STARTING $SERVICE : "

su - $USER -c "$INTERPERTER $EXEC_FILE"
Ret=$?
if [ $Ret -ne 0 ]
then
	log_failure_msg
else
	log_success_msg
fi
;;

'stop')
# Stop service
echo  -en "STOPPING $SERVICE : "
[ -f "$PID_FILE" ] && su - $USER -c "kill -9 `cat $PID_FILE`"
su - $USER -c "ps -edf | grep $EXEC_FILE | grep -v grep | awk '{print \$2}'|xargs kill -9"
[ -f "$PID_FILE" ] && su - $USER -c "rm -f $PID_FILE"
Ret=$?
if [ $Ret -ne 0 ]
then
	log_failure_msg
else
	log_success_msg
fi
;;

'status')
	PROC=$(su - $USER -c "ps -edf | grep $EXEC_FILE | grep -v grep|awk '{print \$2}'")
	PROC=$(echo "$PROC"| tr '\n' ' ')
	[ "$PROC" == " " ] && echo -e "STATUS $SERVICE : not running"
	[ "$PROC" == " " ] || echo -e "STATUS $SERVICE : ($PROC) running..."
;;
'restart')
# Stop the service and regardless of whether it was
# running or not, start it again.
$0 stop
sleep 5s
$0 start
;;

*)
# usage
echo "Usage: $0 start|stop|restart|status"
exit 1
;;
esac
